// 全局变量
let currentPage = 1;
const pageSize = 10;
const CHUNK_SIZE = 1024 * 1024; // 1MB

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadVideos();
});

// 加载视频列表
async function loadVideos() {
    try {
        const response = await fetch(`/api/v1/videos/?skip=${(currentPage-1)*pageSize}&limit=${pageSize}`);
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || '加载失败');
        }
        const videos = await response.json();
        
        const container = document.getElementById('videoContainer');
        container.innerHTML = '';
        
        videos.forEach(video => {
            const videoElement = createVideoElement(video);
            container.appendChild(videoElement);
        });
    } catch (error) {
        console.error('加载视频列表失败:', error);
        showAlert('加载视频列表失败');
    }
}

// 创建视频列表项
function createVideoElement(video) {
    const div = document.createElement('div');
    div.className = 'video-item';
    
    div.innerHTML = `
        <div class="video-info">
            <span>${video.title}</span>
            <span>${formatFileSize(video.file_size)}</span>
        </div>
        <div class="video-actions">
            <button class="play-btn" onclick="playVideo(${video.id}, '${video.title}')">播放</button>
            <button class="delete-btn" onclick="deleteVideo(${video.id})">删除</button>
        </div>
    `;
    
    return div;
}

// 上传视频
async function uploadVideo() {
    const titleInput = document.getElementById('videoTitle');
    const fileInput = document.getElementById('videoFile');
    const progressBar = document.getElementById('uploadProgress');
    const progressElement = progressBar.querySelector('.progress');
    
    if (!fileInput.files[0]) {
        showAlert('请选择视频文件', { type: 'warning' });
        return;
    }
    
    const file = fileInput.files[0];
    
    // 检查文件类型
    if (!file.type.startsWith('video/')) {
        showAlert('请选择视频文件', { type: 'warning' });
        return;
    }
    
    // 如果标题为空，使用文件名（去掉扩展名）
    let title = titleInput.value.trim();
    if (!title) {
        title = file.name.replace(/\.[^/.]+$/, ''); // 移除文件扩展名
        titleInput.value = title; // 更新输入框
    }
    
    try {
        progressBar.style.display = 'block';
        progressElement.style.width = '0%';
        
        if (file.size < 50 * 1024 * 1024) { // 小于50MB
            await uploadSmallFile(file, title, progressElement);
        } else {
            await uploadLargeFile(file, title, progressElement);
        }
        
        showAlert('上传成功', { type: 'success' });
        loadVideos();
        titleInput.value = '';
        fileInput.value = '';
        progressBar.style.display = 'none';
    } catch (error) {
        console.error('上传失败:', error);
        showAlert(error.message || '上传失败');
        progressBar.style.display = 'none';
    }
}

// 上传小文件
async function uploadSmallFile(file, title, progressElement) {
    const formData = new FormData();
    formData.append('title', title);
    formData.append('file', file);

    // 详细的调试信息
    console.log('Upload request details:');
    console.log('Title:', title);
    console.log('File:', file);
    debugger
    console.log('File type:', file.type);
    console.log('File size:', file.size);
    
    console.log('FormData entries:');
    for (let pair of formData.entries()) {
        console.log(pair[0], ':', pair[1]);
        if (pair[1] instanceof File) {
            console.log('File details:', {
                name: pair[1].name,
                type: pair[1].type,
                size: pair[1].size
            });
        }
    }

    try {
        console.log('Sending request to:', '/api/v1/upload/');
        const response = await fetch('/api/v1/upload/', {
            method: 'POST',
            body: formData
        });
        
        console.log('Response status:', response.status);
        console.log('Response headers:', Object.fromEntries(response.headers.entries()));
        
        const responseText = await response.text();
        console.log('Raw response:', responseText);
        
        let responseData;
        try {
            responseData = JSON.parse(responseText);
            console.log('Parsed response data:', responseData);
        } catch (e) {
            console.error('Failed to parse response as JSON:', e);
            throw new Error('Invalid server response');
        }

        if (!response.ok) {
            throw new Error(responseData.detail || '上传失败');
        }
        
        progressElement.style.width = '100%';
    } catch (error) {
        console.error('上传小文件失败:', error);
        throw error;
    }
}

// 上传大文件
async function uploadLargeFile(file, title, progressElement) {
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    
    try {
        for (let i = 0; i < totalChunks; i++) {
            const chunk = file.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
            const formData = new FormData();
            formData.append('title', title);
            formData.append('chunk_number', i.toString());
            formData.append('total_chunks', totalChunks.toString());
            formData.append('file', new Blob([chunk], { type: file.type }), file.name);
            
            const response = await fetch('/api/v1/upload/chunk/', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.detail || `分片 ${i} 上传失败`);
            }
            
            const progress = ((i + 1) / totalChunks) * 100;
            progressElement.style.width = `${progress}%`;
        }
    } catch (error) {
        console.error('上传大文件失败:', error);
        throw error;
    }
}

// 播放视频
function playVideo(videoId, title) {
    const player = document.getElementById('videoPlayer');
    const titleElement = document.getElementById('currentVideoTitle');
    
    // 记录当前播放的视频ID
    player.dataset.currentVideoId = videoId;
    
    // 设置错误处理
    player.onerror = function() {
        showAlert('视频加载失败，正在重试...', { type: 'warning' });
        // 延迟1秒后重试
        setTimeout(() => {
            player.src = `/api/v1/video/${videoId}`;
        }, 1000);
    };
    
    // 添加缓冲提示
    player.onwaiting = function() {
        showAlert('视频正在缓冲...', { 
            type: 'info',
            autoClose: true,  // 自动关闭
            duration: 1000    // 1秒后关闭
        });
    };
    
    // 设置视频源和标题
    player.src = `/api/v1/video/${videoId}`;
    titleElement.textContent = title;
}

// 清空播放器
function clearPlayer() {
    const player = document.getElementById('videoPlayer');
    const titleElement = document.getElementById('currentVideoTitle');
    
    // 移除错误处理函数
    player.onerror = null;
    
    // 暂停播放并清空源
    player.pause();
    player.src = '';
    player.removeAttribute('data-current-video-id');
    
    // 恢复默认提示文本
    titleElement.innerHTML = '<span class="default-text">请从右侧列表选择要播放的视频</span>';
}

// 显示自定义确认框
function showConfirm(message, options = {}) {
    return new Promise((resolve) => {
        const {
            confirmText = '确定',
            cancelText = '取消',
            closeOnEsc = true
        } = options;
        
        const confirmBox = document.getElementById('customConfirm');
        const messageElement = confirmBox.querySelector('.alert-message');
        const confirmBtn = confirmBox.querySelector('.confirm-btn');
        const cancelBtn = confirmBox.querySelector('.cancel-btn');
        
        messageElement.textContent = message;
        confirmBtn.textContent = confirmText;
        cancelBtn.textContent = cancelText;
        
        const handleConfirm = () => {
            closeConfirm();
            resolve(true);
        };
        
        const handleCancel = () => {
            closeConfirm();
            resolve(false);
        };
        
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                handleCancel();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        
        confirmBtn.onclick = handleConfirm;
        cancelBtn.onclick = handleCancel;
        
        if (closeOnEsc) {
            document.addEventListener('keydown', handleEsc);
        }
        
        confirmBox.style.display = 'flex';
    });
}

// 关闭自定义确认框
function closeConfirm() {
    const confirmBox = document.getElementById('customConfirm');
    confirmBox.style.display = 'none';
}

// 修改删除视频函数
async function deleteVideo(videoId) {
    const confirmed = await showConfirm('确定要删除这个视频吗？', {
        confirmText: '删除',
        cancelText: '取消'
    });
    
    if (!confirmed) {
        return;
    }
    
    try {
        const response = await fetch(`/api/v1/video/${videoId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || '删除失败');
        }
        
        // 如果删除的是当前正在播放的视频，清空播放器
        const player = document.getElementById('videoPlayer');
        if (player.dataset.currentVideoId === videoId.toString()) {
            clearPlayer();
        }
        
        showAlert('删除成功', { type: 'success' });
        loadVideos();
    } catch (error) {
        console.error('删除失败:', error);
        showAlert(error.message || '删除失败', { type: 'error' });
    }
}

// 加载上一页
function loadPreviousPage() {
    if (currentPage > 1) {
        currentPage--;
        document.getElementById('currentPage').textContent = currentPage;
        loadVideos();
    }
}

// 加载下一页
function loadNextPage() {
    currentPage++;
    document.getElementById('currentPage').textContent = currentPage;
    loadVideos();
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示自定义弹框，支持类型和自定义选项
function showAlert(message, options = {}) {
    const {
        type = 'info',
        buttonText = '确定',
        closeOnEsc = true,
        autoClose = false,
        duration = 3000
    } = options;
    
    const alertBox = document.getElementById('customAlert');
    const messageElement = alertBox.querySelector('.alert-message');
    const button = alertBox.querySelector('button');
    
    messageElement.textContent = message;
    button.textContent = buttonText;
    alertBox.className = `custom-alert ${type}`;
    alertBox.style.display = 'flex';
    
    if (autoClose) {
        setTimeout(() => {
            closeAlert();
        }, duration);
    }
    
    if (closeOnEsc) {
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                closeAlert();
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    }
}

// 关闭自定义弹框
function closeAlert() {
    document.getElementById('customAlert').style.display = 'none';
} 